package com.luban.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 同步非阻塞
 * @ClassName NioServer
 * @Description 498982703@qq.com
 * @Author gary
 * @Date 2021/2/19 9:25
 * @Version 1.0
 */
public class NioServer {
    static List<SocketChannel> channelList = new ArrayList<>(1000);

    public static void main(String[] args) throws IOException {
        //create serverSocketChannel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().bind(new InetSocketAddress(9000));
        //set noblocking
        serverSocketChannel.configureBlocking(false);
        System.out.println("server start");
        while (true){
            // 非阻塞模式accept方法不会阻塞，否则会阻塞
            // NIO的非阻塞是由操作系统内部实现的，底层调用了linux内核的accept函数
            SocketChannel socket = serverSocketChannel.accept();
            if (socket != null) {
                System.out.println("link access");
                socket.configureBlocking(false);
                channelList.add(socket);
            }
            Iterator<SocketChannel> iterator = channelList.iterator();
            while (iterator.hasNext()) {
                SocketChannel nextSocket = iterator.next();
                ByteBuffer byteBuffer = ByteBuffer.allocate(128);
                int len = nextSocket.read(byteBuffer);
                if (len > 0) {
                    System.out.println("accept message:" + new String(byteBuffer.array()));
                }else if(len ==-1) {
                    iterator.remove();
                    System.out.println("shut down client link");

                }
            }
        }

    }
}
